package org.spring.springboot.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class ImageController {
	@RequestMapping(value = "uploadfile", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam("test_file") MultipartFile file, HttpServletRequest request) throws Exception {
		
		
		// 分别获取的是变量名file---文件类型---文件名
		System.out.println(file.getName() + "---" + file.getContentType() + "---" + file.getOriginalFilename());
		int last = file.getOriginalFilename().lastIndexOf(".");
		System.out.println(last);
		String filename = file.getOriginalFilename().substring(last);
		System.out.println(filename);
		String path = request.getSession().getServletContext().getRealPath("")+"test";
		//如果不存在文件夹就创建
		File file1111 = new File(path);
		if(!file1111.exists()){
			new File(path).mkdirs();
		}
		String realpath = "";
		String realpath1 = "";
		try {
			if (!file.isEmpty()) {
				// 使用StreamsAPI方式拷贝文件
				System.out.println("\\a\\" + file.getOriginalFilename());
			 realpath = path + "\\" +"bbb"+ file.getOriginalFilename();
			 realpath1 = System.currentTimeMillis()+ file.getOriginalFilename();
				Streams.copy(file.getInputStream(), new FileOutputStream(realpath),
						true);
			}
		} catch (IOException e) {
			System.out.println("文件上传失败");
			e.printStackTrace();
		}
		return "hhhhh"+ file.getOriginalFilename();
	}
		
}
